<script setup>
import { ref, reactive, onMounted,computed } from 'vue';
import { useRouter } from 'vue-router';
import { eventApi, eventnodeuserApi,flowById } from '@/service/api.ts';
import { isJSON } from '@/utils/utils.ts';
import { useConstValue, useLocalValue, useIuserInfoStore } from '@/store/users.ts';
import dayjs from 'dayjs';
import SheetSvg from '~icons/svg/sheet';
import PraiseSvg from '~icons/svg/praise';

const router = useRouter();
const constValue = useConstValue();
const localValue = useLocalValue();
const iuserInfoStore = useIuserInfoStore();
const { info } = iuserInfoStore;

const tabRt = reactive({
  tabs: ['进行中项目', '已公示项目'],
  tab: 0,
});

onMounted(() => {
  init();
});

const labelMap = [
  '',
  '',
];
const identities = ['业主', '业主代表', '业委会成员', '业委会主任'];
let labelIsStatus = ["公示中", "审核拒绝", '业委会投票否决',]
const list = ref([]);
const stepInfo = ref([])

const stepListInfo = computed(() => {
  if (!stepInfo.value.length) {
    return []
  }
  // let topStep = stepInfo.value.filter(item => item.type === 'first')
  // let centerStep = stepInfo.value.filter(item => item.type === 'center')
  // centerStep = centerStep.sort((a, b) => a.y - b.y)
  // let endStep = stepInfo.value.filter(item => item.type === 'end').slice(0, 1)
  return stepInfo.value.sort((a, b) => a.y - b.y)
})

const showNextNode = (nodename,nodeId)=>{
  
  if(!stepListInfo.value.length){
    return ''
  }
  let nowNode = stepListInfo.value.findIndex((item)=>item.properties.sql_id == nodeId)
  console.log('nowNode',nowNode);

  if(nodename.includes('中') && !nodename.includes('公示')){
    nowNode = stepListInfo.value.findIndex((item,index)=> index > nowNode && item.type !== 'end')
  }

  if(nowNode !== -1){
    return stepListInfo.value[nowNode].text.value
  }
  if(nowNode == -1){
    return ''
  }
}
const init = async () => {
  const data = await flowById({ method: 'get', id: constValue.flowID });
  if (data?.fron_data?.nodes) {
    stepInfo.value = data?.fron_data?.nodes.sort((a, b) => a.properties.sql_id - b.properties.sql_id)
  } else {
    stepInfo.value = []
  }
  const type = labelMap[tabRt.tab];
  list.value = [];
  const events = await getEventIngList(type);
  
  events.sort((a, b) => {
    return new Date(b.create_time) - new Date(a.create_time) < 0 ? -1 : 1;
  });
  
  for (let i = 0; i <= events.length - 1; i++) {
    const event = events[i];
    const arrs = event.form_data ? JSON.parse(event.form_data) : [];
    const request_params = event.request_params ? JSON.parse(event.request_params) : [];
    const signs = arrs.length ? arrs.filter(item => item.sign) : [];
    event._sign = {};
    signs.forEach(item => {
      event._sign[item.sign] = item.value;
    });
    event._form_data = arrs.filter(i => !i.sign);
    event.request_params = request_params;
    console.log('event.status', event.status);

    if (event.status.includes('已结束') || labelIsStatus.includes(event.status)) {
      if (tabRt.tab) {
        list.value.push(event);
      }
    } else {
      if (!tabRt.tab) {
        list.value.push(event);
      }
    }
  }
}
const initCopy = async () => {
  const type = labelMap[tabRt.tab];
  list.value = [];
  let events = await getEventIngList(type);

  events.sort((a, b) => {
    return new Date(b.create_time) - new Date(a.create_time) < 0 ? -1 : 1;
  });
  
  for (let i = 0; i <= events.length - 1; i++) {
    const event = events[i];
    if (!isJSON(event.form_data)) {
      continue;
    }
    const arrs = JSON.parse(event.form_data);
    const request_params = event.request_params ? JSON.parse(event.request_params) : [];
    const signs = arrs.filter(item => item.sign);
    if (!signs.length) {
      continue;
    }
    event._sign = {};
    signs.forEach(item => {
      event._sign[item.sign] = item.value;
    });
    event._form_data = arrs.filter(i => !i.sign);
    event.request_params = request_params;
    // const nodeusers = await getEventnodeuserList(event);
    // if (nodeusers?.length) {
    //   event._vote = nodeusers[0].mark;
    // }

    const dex1 = identities.indexOf(localValue.mainUser.user_identity);
    const dex2 = identities.indexOf(event._sign?.identity);
    if (dex1 >= dex2) {
      list.value.push(event);
    }
    list.value.push(event);
  }
}
const getEventIngList = (type) => {
  return new Promise((resolve, reject) => {
    eventApi({
      method: 'get',
      params: {
        project: constValue.projectID,
        flow: constValue.flowID,
        node__before_node__form__type: type,
      }
    }).then(res => {
      resolve(res?.results || []);
    }).catch(err => {
      reject([]);
    })
  })
}
// const getEventnodeuserList = (event) => {
//   return new Promise((resolve, reject) => {
//     eventnodeuserApi({
//       method: 'get',
//       params: {
//         project: constValue.projectID,
//         event: event.id,
//         node: event.node,
//       }
//     }).then(res => {
//       resolve(res?.results || []);
//     }).catch(err => {
//       reject([]);
//     })
//   })
// }

const handleEnter = (event) => {
  router.push({ path: '/businessCommittee/busComtUser', query: { eventID: event.id, tab: tabRt.tab } });
}
</script>

<template>
  <div class="content flex-column">
    <div class="tabs flex-sb">
      <div v-for="(item, index) in tabRt.tabs" :class="{ 'isActive': index === tabRt.tab }"
        @click="tabRt.tab = index; init()">
        <span>{{ item }}</span>
      </div>
    </div>

    <div class="list-box scroller-aside">
      <div class="card flex-column" v-for="event in list" @click="handleEnter(event)">
        <div class="card-title flex--center">
          <div class="ellipsis flex-sb" style="flex: 1;">
            <div style="    padding-right: 50px;">{{ event?.name }}</div>
            <div class="ellipsis-status flex--center" style="flex: 1;overflow: hidden;"> 
              <div style="margin-right: 2px;flex:1;overflow: hidden;text-overflow: ellipsis;text-align: right;" v-if="event?.node">{{ event?.status.includes('结束') && !event?.status.includes('征询')? event?.status: showNextNode(event?.status,event?.node) }} </div>
              <van-icon name="arrow" size="20" />
            </div>
          </div>
          <!-- <div
            class="text flex-nowrap flex--center"
            :class="{ 'neg': event._vote === '反对'}"
            v-if="event._vote"
          >
            <PraiseSvg />
            <span>已{{ event._vote }}</span>
          </div> -->
        </div>
        <div class="time-row flex" v-if="event.request_params[0]">
          <label class="form-item">项目内容</label>
          <div class="row-value flex-column ellipsis-3">
            {{ event?.request_params[0].value }}
          </div>
        </div>
        <div class="time-row flex">
          <label class="form-item">项目状态</label>
          <div class="row-value flex-column">
            {{ event?.status }}
          </div>
        </div>
        <div class="time-row flex">
          <label class="form-item">创建时间</label>
          <div class="row-value flex-column" v-if="event._sign">
            {{ event?.create_time }}
          </div>
        </div>
      </div>
      <div class="card flex-column default-card" v-if="!list.length">
        暂无项目
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.content {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(180deg, #D1E9FF 0%, rgba(209, 233, 255, 0) 25%, #F7F7F7 30%);
}

.tabs {
  padding: 10px 65px;
  font-weight: 500;
  font-size: 16px;
  color: #666666;

  &>div {
    flex: 1;
    text-align: center;
    padding: 10px 0;
  }

  .isActive {
    color: #165DFF;
    position: relative;
    font-weight: 500;

    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      width: 24px;
      height: 2px;
      background-color: #165DFF;
      transform: translateX(-50%);
    }
  }
}

.list-box {
  flex: 1;
  overflow: auto;
  padding: 12px;
}

.card {
  background: #FFFFFF;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 10px;
}

.default-card {
  text-align: center;
  padding: 30px 0;
  min-height: 80vh;
  line-height: 80vh;
}

.card-title {
  padding: 0 12px;
  font-weight: 500;
  font-size: 16px;
  color: #333333;

  span {
    margin-left: 5px;
  }

  // .text {
  //   color: #00B578;
  //   font-size: 14px;
  //   svg {
  //     width: 16px;
  //     height: 16px;
  //     margin-right: 4px;
  //   }
  //   &.neg {
  //     color: #FF0000;
  //     svg {
  //       transform-origin: center;
  //       transform: rotate(180deg);
  //     }
  //   }
  // }
  .ellipsis {
    padding: 12px 0;
    border-bottom: 1px solid #F8F8F8;

    .ellipsis-status {
      color: #1F89FF;
      font-size: 14px;
    }
  }
}

.time-row {
  padding: 12px 12px 0;
}

.time-row:last-child {
  padding: 12px;
}

label.form-item {
  width: 60px;
  min-width: 60px;
  white-space: nowrap;
  margin-left: 4px;
  font-size: 14px;
  color: #666666;
  margin-right: 12px;
}

.row-value {
  font-size: 14px;
  color: #111111;
  display: -webkit-box;
  /* 启用 WebKit 的弹性布局 */
  -webkit-line-clamp: 3;
  /* 限制内容显示三行 */
  -webkit-box-orient: vertical;
  /* 垂直布局 */
  overflow: hidden;
  /* 隐藏超出部分 */
  text-overflow: ellipsis;
  /* 显示省略号 */
  word-break: break-word;
  /* 防止长单词溢出 */
}

.others-box {
  padding: 0 12px 6px;

  .other-item {
    margin: 6px 0;
  }
}
</style>